package com.fita.webpay.processor.impl;

import java.math.BigDecimal;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.entity.pay.PayConfig;
import com.fita.webpay.entity.PayType;
import com.fita.webpay.entity.PaymentContext;
import com.fita.webpay.entity.config.YoppayConfig;
import com.fita.webpay.entity.prepare.PrepareResponse;
import com.fita.webpay.processor.PaymentProcessor;
import com.yeepay.g3.sdk.yop.client.YopRequest;
import com.yeepay.g3.sdk.yop.client.YopResponse;
import com.yeepay.g3.sdk.yop.client.YopRsaClient;

@Component("yoppayProcessor")
public class YoppayProcessor implements PaymentProcessor {

    private static final Logger logger = LoggerFactory.getLogger(WechatpayProcessor.class);
    
    private YoppayConfig yoppayConfig;
    
    @Autowired
    public void initConfig(@Value("#{payment['yop.appId']}") String appId,
                                    @Value("#{payment['yop.partnerId']}") String partnerId,
                                    @Value("#{payment['yop.notifyUrl']}") String notifyUrl,
                                    @Value("#{payment['yop.proertiesPath']}") String proertiesPath){
        
        // init static configurations
        this.yoppayConfig = new YoppayConfig(appId, partnerId, notifyUrl);
        
        // "file:///Users/mohanlan/Desktop/yop_sdk_config_default.json"
        System.setProperty("yop.sdk.config.file", proertiesPath);
        
    }
    
    /*
     * (non-Javadoc)
     * @see com.fita.webpay.processor.PaymentProcessor#prepare(com.fita.webpay.entity.PaymentContext)
     */
    public PrepareResponse prepare(PaymentContext paymentContext) {
        
        logger.info("get config [{}]", System.getProperty("yop.sdk.config.file"));
        PrepareResponse prepareResponse = new PrepareResponse();
        
        try {
            
            
            
            YopRequest request = new YopRequest();
            
            // generate request for every type
            PayType payType = PayType.codeOf(paymentContext.getChannelType());
            if(payType.isWechat()) {
                request = this.generateWechatRequest();
                request.addParam("openId", paymentContext.getUserId());
            } else if (payType.isPc()) {
                request = this.generatePCRequest();
            } else if (payType.isAlipay()) {
                request = this.generateAlipayRequest();
            }
            
            BigDecimal amount = new BigDecimal(paymentContext.getAmount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            logger.info("get current amount[{}]", amount.doubleValue());
            // generate order params
            request.addParam("amount", amount.doubleValue());           //交易金额
            request.addParam("goodsName", paymentContext.getSubject()); // 商品名称
            request.addParam("goodsDesc", "商户订单：" + paymentContext.getOrderCode());//商户退款请求订单号
            request.addParam("customerRequestNo", paymentContext.getToken());//商户请求订单号
            request.addParam("frontUrl", paymentContext.getCallbackUrl());//商户前端回调地址
            
            YopResponse response = YopRsaClient.post("/rest/v1.0/bc/cashier/create-yop-cashier-url", request);//发送报文
            
            if(!response.isSuccess()) {
                logger.info("call yoppay get result msg [{}]", response.toString());
                prepareResponse.fail().message("创建易宝支付环境失败!");
                return prepareResponse;
            }
            
            Map<String, Object> result = JsonUtils.parse(JsonUtils.toJson(response.getResult()));
            prepareResponse.success().data("url", result.get("cashierUrl").toString());
            
            
        } catch (Exception e) {
            prepareResponse.fail().message("创建易宝支付环境失败!");
            
        }
        
        logger.info("prepare success with result [{}]", JsonUtils.toJson(prepareResponse));
        
        return prepareResponse;
        
        // generate params here for yop
//        YopRequest request = new YopRequest();
//        logger.info("get yop pay config key [{}] server [{}]", request.getAppSdkConfig().getAesSecretKey(), request.getAppSdkConfig().getServerRoot());
//        request.addParam("customerNo","10027789638");//商编
//        request.addParam("amount","0.02");//商户原交易订单号
//        request.addParam("goodsName","测试新");//商户退款请求订单号
//        request.addParam("customerRequestNo","2019"+System.currentTimeMillis());//商户请求订单号
//        request.addParam("frontUrl","www.baidu.com");//商户前端回调地址
//        request.addParam("receiverCallbackUrl","www.yeepay.com");//异步回调地址
//        request.addParam("accountWay","COMMON");//入账方式 COMMON：普通入账担保入账传该值 SPLIT 分账入账
//        request.addParam("accountType","REAL_TIME");//入账类型实时入账（REAL_TIME）担保入账（ASSURE）
//        
//        // PC
//        request.addParam("wechatYhsmBankCode", "OFFLINE");
//        request.addParam("alipayYhsmBankCode", "OFFLINE");
//        
//        // MOBILE
//        request.addParam("bankCode", "OFFLINE");
//        request.addParam("directPayType", "ZF_GZH");
//        request.addParam("appId", "wx25809103fe54c3c7");
//        request.addParam("openId", "oJ9WO1oV1YFBM5VwtAhtoX5I9dwQ");
//        
//        try {
//            
//            YopResponse response = YopRsaClient.post("/rest/v1.0/bc/cashier/create-yop-cashier-url", request);//发送报文
//            
////            CheckUtils.checkApiUri("/rest/v1.0/bc/cashier/create-yop-cashier-url");
////          
//            System.out.println(response.toString());
//        } catch (IOException e) {
//            logger.error("call yop get error: ", e);
//        }//发送报文
//        
//        return null;
    }
    
    private YopRequest generatePCRequest() {
     // generate params here for yop
        YopRequest request = new YopRequest();
        request.addParam("customerNo", yoppayConfig.getSellerId());//商编
        request.addParam("receiverCallbackUrl", yoppayConfig.getNotifyUrl());//异步回调地址
        request.addParam("accountWay", yoppayConfig.getAccountWany());//入账方式 COMMON：普通入账担保入账传该值 SPLIT 分账入账
        request.addParam("accountType", yoppayConfig.getAccountType());//入账类型实时入账（REAL_TIME）担保入账（ASSURE）
        
        // PC
//        request.addParam("directPayType", "NCPAY");
        request.addParam("wechatYhsmBankCode", yoppayConfig.getWechatYhsmBankCode());
        request.addParam("alipayYhsmBankCode", yoppayConfig.getAlipayYhsmBankCode());
        
        return request;
    }
    
    /**
     * 
     * @return
     */
    private YopRequest generateWechatRequest() {
        
        YopRequest request = new YopRequest();
        request.addParam("customerNo", yoppayConfig.getSellerId());//商编
        request.addParam("receiverCallbackUrl", yoppayConfig.getNotifyUrl());//异步回调地址
        request.addParam("accountWay", yoppayConfig.getAccountWany());//入账方式 COMMON：普通入账担保入账传该值 SPLIT 分账入账
        request.addParam("accountType", yoppayConfig.getAccountType());//入账类型实时入账（REAL_TIME）担保入账（ASSURE）

        // MOBILE
        request.addParam("bankCode", yoppayConfig.getBankCode());
        request.addParam("directPayType", "ZF_GZH");
        request.addParam("appId", yoppayConfig.getAppid());
        //request.addParam("openId", "oJ9WO1oV1YFBM5VwtAhtoX5I9dwQ");
        
        return request;
    }
    
    /**
     * 
     * @return
     */
    private YopRequest generateAlipayRequest() {
        
        YopRequest request = new YopRequest();
        request.addParam("customerNo", yoppayConfig.getSellerId());//商编
        request.addParam("receiverCallbackUrl", yoppayConfig.getNotifyUrl());//异步回调地址
        request.addParam("accountWay", yoppayConfig.getAccountWany());//入账方式 COMMON：普通入账担保入账传该值 SPLIT 分账入账
        request.addParam("accountType", yoppayConfig.getAccountType());//入账类型实时入账（REAL_TIME）担保入账（ASSURE）

        // MOBILE
        request.addParam("bankCode", yoppayConfig.getBankCode());
        request.addParam("directPayType", "ZFB_SHH");
        request.addParam("appId", yoppayConfig.getAppid());
        //request.addParam("openId", "oJ9WO1oV1YFBM5VwtAhtoX5I9dwQ");
        
        return request;
    }

    /*
     * (non-Javadoc)
     * @see com.fita.webpay.processor.PaymentProcessor#validate(com.demo2do.core.wechat.entity.pay.PayConfig)
     */
    public boolean validate(PayConfig payConfig) {
        // 此方法在此无用
        return false;
    }

}
